<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="用户名" class="row-padding-bottom">
              <el-input
                v-model="filterField.nickName"
                placeholder="请输入用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="操作时间" class="row-padding-bottom">
              <timeSelection
                @getStartTimeValue="getStartTimeValue"
                @getEndTimeValue="getEndTimeValue"
              ></timeSelection>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="登录用户" class="row-padding-bottom">
                <el-input
                  v-model="filterField.userName"
                  placeholder="请输入登录用户名"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="用户类型" class="row-padding-bottom">
                <el-select
                  v-model="filterField.userType"
                  filterable
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in userTypeList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="操作类型" class="row-padding-bottom">
                <el-select
                  v-model="filterField.type"
                  filterable
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in actionList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item label="">
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              v-sdc
              @click="exportList"
            >
              <span class="opetareText">导出</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          :data="tableList"
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
          border
        >
          <el-table-column
            prop="userName"
            width="140px"
            align="center"
            label="登录用户"
            :formatter="formatTd"
          />
          <el-table-column
            prop="nickName"
            width="230px"
            label="用户名"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.nickName"
                :columnName="'nickName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="userTypeName"
            align="center"
            width="120px"
            label="用户类型"
            :formatter="formatTd"
          />
          <el-table-column
            prop="updateTime"
            align="center"
            label="操作时间"
            sortable="custom"
            :formatter="formatTd"
            width="180px"
          />
          <el-table-column
            prop="clientIp"
            align="center"
            width="140px"
            label="ip地址"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <el-tooltip placement="right" effect="dark">
                <div slot="content">{{ ipAddress }}</div>
                <el-link
                  @mouseenter.native="getIPAddress(scope.row.clientIp)"
                  >{{ scope.row.clientIp }}</el-link
                >
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeName"
            align="center"
            min-width="100px"
            label="操作类型"
            :formatter="formatTd"
          />
          <el-table-column
            prop="browser"
            align="center"
            min-width="100px"
            label="操作环境"
            :formatter="formatTd"
          />
          <el-table-column
            prop="function"
            label="操作内容(操作简介)"
            :formatter="formatTd"
            width="230px"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.function"
                :columnName="'function'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="left"
            fixed="right"
            width="110px"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看详情</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关专户数据"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>

    <el-drawer
      title="日志详情"
      :visible.sync="showLog"
      :direction="direction"
      size="800px"
      :before-close="handleClose"
    >
      <div class="logInfo">
        <div class="baseInfo">
          <el-row>
            <el-col :span="12"
              >操作类型：{{ tableListLog.typeName || '--' }}</el-col
            >
            <el-col :span="12"
              >登录用户：{{ tableListLog.userName || '--' }}</el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12"
              >用户名：{{ tableListLog.nickName || '--' }}</el-col
            >
            <el-col :span="12"
              >用户类型：{{ tableListLog.userTypeName || '--' }}</el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12"
              >操作时间：{{ tableListLog.updateTime || '--' }}</el-col
            >
            <el-col :span="12"
              >IP地址：{{ tableListLog.clientIp || '--' }}</el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12"
              >登录地区：{{ tableListLog.address || '--' }}</el-col
            >
            <el-col :span="12"
              >操作环境：{{ tableListLog.browser || '--' }}</el-col
            >
          </el-row>
          <el-row>
            <el-col :span="24"
              >操作内容：{{ tableListLog.function || '--' }}</el-col
            >
          </el-row>
        </div>
        <div class="responseInfo">
          <span>请求体:</span>
          <div v-if="tableListLog.requestBody">
            <vue-markdown
              :source="tableListLog.requestBody"
              class="wwww"
            ></vue-markdown>
          </div>
        </div>
        <div class="responseInfo">
          <span>响应体:</span>
          <div v-if="tableListLog.responseBody">
            <vue-markdown
              :source="tableListLog.responseBody"
              class="wwww"
            ></vue-markdown>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import VueMarkdown from 'vue-markdown'
import common from '../../kits/common'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'loginLog',
  mixins: [scrollTable],
  components: {
    VueMarkdown,
  },
  data() {
    return {
      advanced: false,
      //表格数据
      tableList: [],
      requestUrl: 'api-m/sysLog/base/page',
      date: [],
      actionList: [],
      userTypeList: [
        { name: '企业用户', code: '企业用户' },
        { name: '个人用户', code: '个人用户' },
      ],
      //搜索条件
      filterField: {
        usingMenu: 'LOGIN_LOG', //项目名称
        userName: '', //专户账号
        updateStartTime: '', //区域
        updateEndTime: '', //行业
        nickName: '',
        userType: '',
        type: '',
      },
      pageSize: 20,
      pageNum: 1,
      isShow: false, //列表加载
      loading: false,

      showLog: false,
      tableListLog: {
        typeName: '',
        userName: '',
        nickName: '',
        userTypeName: '',
        updateTime: '',
        clientIp: '',
        function: '',
        requestBody: '',
        responseBody: '',
        address: '',
        browser: '',
      },
      ipAddress: 'cs地址',
    }
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
      // this.$refs.tableBox1&&this.$refs.tableBox1.doLayout()
    })
    this.getActionType()
    this.getUserType()
  },
  mounted() {
    this.$nextTick(function () {
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    //获取操作类型集合
    getActionType() {
      this.axios.get('api-m/sysLog/base/operationType').then((res) => {
        if (!res.data.hasError) {
          let obj = res.data.result
          this.actionList = obj.filter((item) =>
            ['登录', '登出'].includes(item.name)
          )
        }
      })
    },
    //获取用户类型集合
    getUserType() {
      this.axios.get('api-m/users/allTypes').then((res) => {
        if (!res.data.hasError) {
          this.userTypeList = res.data.result
        }
      })
    },
    closeDialog() {
      this.showLog = false
    },
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValue(val) {
      if (val) {
        this.filterField.updateStartTime = val
      } else {
        this.filterField.updateStartTime = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValue(val) {
      if (val) {
        this.filterField.updateEndTime = val
      } else {
        this.filterField.updateEndTime = ''
      }
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          this.tableHeight = window.innerHeight - 218
          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNum = val
    },
    exportList() {
      if (this.tableList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-m/sysLog/base/export?usingMenu=LOGIN_LOG&userName=' +
          encodeURIComponent(this.filterField.userName) +
          '&updateStartTime=' +
          this.filterField.updateStartTime +
          '&updateEndTime=' +
          this.filterField.updateEndTime +
          '&nickName=' +
          this.filterField.nickName +
          '&userType=' +
          this.filterField.userType +
          '&type=' +
          this.filterField.type +
          '&sortField=' +
          this.filterField.sortField +
          '&sort=' +
          this.filterField.sort +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'error',
          message: '无数据导出',
        })
      }
    },
    toDetail(item) {
      const { typeName, userName, nickName, userTypeName, browser } = item
      this.axios
        .post('api-m/sysLog/base/detail', { id: item.id })
        .then((res) => {
          if (!res.data.hasError) {
            let { updateTime, clientIp, requestBody, responseBody } =
              res.data.result
            if (requestBody && requestBody != '{}') {
              let arr = requestBody.split(',')
              requestBody = arr.join(',<br>')
              requestBody = requestBody.replaceAll(/{/g, '{<br>')
              requestBody = requestBody.replaceAll(/}/g, '<br>}')
            }
            if (responseBody && responseBody != '{}') {
              let arr = responseBody.split(',')
              responseBody = arr.join(',<br>')
              responseBody = responseBody.replace(/{/g, '{<br>')
              responseBody = responseBody.replaceAll(/}/g, '<br>}')
            }
            this.tableListLog.typeName = typeName
            this.tableListLog.browser = browser
            this.tableListLog.userName = userName
            this.tableListLog.nickName = nickName
            this.tableListLog.userTypeName = userTypeName
            this.tableListLog.updateTime = updateTime
            this.tableListLog.clientIp = clientIp
            this.tableListLog.requestBody = requestBody
            this.tableListLog.responseBody = responseBody
            this.tableListLog.function = res.data.result.function
            this.tableListLog.function = res.data.result.function
            this.getAreaByIp(clientIp)
            this.showLog = true
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
          }
        })
    },
    getAreaByIp(ip) {
      this.axios
        .get('ip2address', { params: { ip, accessKey: 'alibaba-inc' } })
        .then((res) => {
          if (res.data.code == 0) {
            const { country, region, city } = res.data.data
            if (country == 'XX') {
              this.tableListLog.address = city
            } else {
              if (region == city) {
                this.tableListLog.address = country + region
              } else {
                this.tableListLog.address = country + region + city
              }
            }
          } else {
            this.tableListLog.address = ''
          }
        })
    },
    getIPAddress(ip) {
      this.axios
        .get('ip2address', { params: { ip, accessKey: 'alibaba-inc' } })
        .then((res) => {
          if (res.data.code == 0) {
            const { country, region, city } = res.data.data
            if (country == 'XX') {
              this.ipAddress = '登陆地区：' + city
            } else {
              if (region == city) {
                this.ipAddress = '登陆地区：' + country + region
              } else {
                this.ipAddress = '登陆地区：' + country + region + city
              }
            }
          } else {
            this.ipAddress = '登陆地区：' + '--'
          }
        })
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
      this.$refs.tableBox1 && this.$refs.tableBox1.doLayout()
    })
  },
}
</script>

<style scoped lang="less">
.download {
  position: absolute;
  right: 30px;
  top: 0;
}
.mainCon {
  top: 198px;
}

/deep/.el-drawer__header {
  margin-bottom: 0px;
  padding: 20px 24px;
  background-color: #f5f7fa;
}
/deep/.el-drawer__body {
  padding: 24px;
}
.baseInfo {
  background-color: #f5f7fc;
  line-height: 30px;
  color: #666;
  border-right: 1px solid #d5dfe8;
  border-bottom: 1px solid #d5dfe8;
  .el-col {
    padding: 7px 15px;
    border-top: 1px solid #d5dfe8;
    border-left: 1px solid #d5dfe8;
  }
}
.responseInfo {
  padding: 10px 24px 10px 80px;
  position: relative;
  line-height: 30px;
  color: #666;
  margin-top: 15px;
  background-color: #f5f7fc;
  min-height: 150px;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #d5dfe8;
  span {
    position: absolute;
    line-height: 30px;
    height: 30px;
    top: 10px;
    left: 24px;
    color: #333;
  }
  p {
    word-break: break-all;
  }
}
@import '../../../static/css/filterArea.less';
</style>
